<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header" class="questions-title">
          <span>{{$route.query.id?'试题修改':'试题录入'}}</span>
        </div>
        <!-- 录入信息 -->
        <div class="questions-item">
          <el-form
            :model="data"
            :rules="rules"
            ref="form"
            status-icon
            label-width="100px"
            size="small"
          >
            <!-- 学科 -->
            <el-form-item label="学科:" prop="subjectID">
              <el-select
                v-model="data.subjectID"
                @change="subToDir"
                placeholder="请选择"
                style="width:400px"
                clearable
              >
                <el-option
                  v-for="item in subjectList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 目录 -->
            <el-form-item label="目录:" prop="catalogID">
              <el-select v-model="data.catalogID" placeholder="请选择" style="width:400px" clearable>
                <el-option
                  v-for="item in subToDirList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.directoryName"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 企业 -->
            <el-form-item label="企业:" prop="enterpriseID">
              <el-select
                v-model="data.enterpriseID"
                placeholder="请选择"
                style="width:400px"
                clearable
              >
                <el-option
                  v-for="item in companysList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.company"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 城市 -->
            <el-form-item label="城市:" prop="province">
              <el-select v-model="data.province" placeholder="请选择" style="width:190px" clearable>
                <el-option v-for="item in provincesList" :key="item" :value="item" :label="item"></el-option>
              </el-select>
              <el-select v-model="data.city" placeholder="请选择" style="margin-left: 5px;" clearable>
                <el-option v-for="item in citysList" :key="item" :value="item" :label="item"></el-option>
              </el-select>
            </el-form-item>
            <!-- 方向 -->
            <el-form-item label="方向:" prop="direction">
              <el-select v-model="data.direction" placeholder="请选择" style="width:400px" clearable>
                <el-option v-for="item in directionList" :key="item" :value="item" :label="item"></el-option>
              </el-select>
            </el-form-item>
            <!-- 题型 -->
            <el-form-item label="题型:" prop="questionType">
              <el-radio-group v-model="data.questionType">
                <el-radio label="1">单选</el-radio>
                <el-radio label="2">多选</el-radio>
                <el-radio label="3">简答</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 难度 -->
            <el-form-item label="难度:" prop="difficulty">
              <el-radio-group v-model="data.difficulty">
                <el-radio label="1">简单</el-radio>
                <el-radio label="2">一般</el-radio>
                <el-radio label="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 题干 -->
            <el-form-item label="题干：" label-width="108px" prop="question">
              <quill-editor v-model="data.question" @blur="checkContent" :options="editorOption"></quill-editor>
            </el-form-item>
            <!-- 选项 -->
            <el-radio-group v-model="isRight" @change="makeSureIsRight" v-if="data.questionType==1">
              <el-form-item label="选项:">
                <div
                  v-for="(item,index) in data.options"
                  :key="'radio'+index"
                  style="margin-top:10px"
                >
                  <el-radio
                    checked
                    name="radio"
                    :label="index"
                    v-model="data.options"
                  >{{index|numberToCode}}:</el-radio>
                  <el-input v-model="item.title" style="width:300px"></el-input>
                  <el-upload
                    class="avatar-uploader"
                    action
                    :show-file-list="false"
                    :on-success="upSuccess"
                    :before-upload="befUpload"
                  >
                    <p>上传图片</p>
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <i class="el-icon-circle-close del-ico"></i>
                  </el-upload>
                </div>
                <el-row class="addBtn">
                  <el-button type="danger" @click="addSelectItem" disabled="disabled">+增加选项与答案</el-button>
                </el-row>
              </el-form-item>
            </el-radio-group>
            <!-- 多选 -->
            <el-form-item label="选项:" v-if="data.questionType==2">
              <div
                v-for="(item,index) in data.options"
                :key="'checkbox'+index"
                style="margin-top:10px"
              >
                <el-checkbox v-model="item.isRight">{{index|numberToCode}}:</el-checkbox>
                <el-input v-model="item.title" style="width:300px"></el-input>
                <el-upload
                  class="avatar-uploader"
                  action
                  :show-file-list="false"
                  :on-success="upSuccess"
                  :before-upload="befUpload"
                >
                  <p>上传图片</p>
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <i class="el-icon-circle-close del-ico"></i>
                </el-upload>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="delSelectItem(index)"
                  circle
                  style="margin-left:50px"
                ></el-button>
              </div>
              <el-row class="addBtn">
                <el-button type="danger" @click="addSelectItem">+增加选项与答案</el-button>
              </el-row>
            </el-form-item>
            <!-- 解析视频 -->
            <el-form-item label="解析视频:">
              <el-input v-model="data.videoURL" clearable style="width:400px"></el-input>
            </el-form-item>

            <!-- 答案解析 -->
            <el-form-item label="答案解析：" label-width="108px" prop="answer">
              <quill-editor v-model="data.answer" @blur="checkContent" :options="editorOption"></quill-editor>
            </el-form-item>
            <!-- 试题备注 -->
            <el-form-item label="试题备注:" prop="remarks">
              <el-input type="textarea" v-model="data.remarks" style="width:400px"></el-input>
            </el-form-item>
            <!-- 试题标签 -->
            <el-form-item label="试题标签:" prop="tags">
              <el-select v-model="data.tags" placeholder="请选择试题标签" style="width:400px" clearable>
                <el-option
                  v-for="item in subToTgList"
                  :key="item.id"
                  :value="item.id|toString"
                  :label="item.tagName"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 确认按钮 -->
            <el-form-item v-if="$route.query.id">
              <el-button type="success" @click="editQuestions">确认修改</el-button>
            </el-form-item>
            <el-form-item v-else>
              <el-button type="primary" @click="onSubmit('form')">确认提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
import { simple } from "@/api/hmmm/subjects";
import { list as listDir } from "@/api/hmmm/directorys";
import { list as listCom } from "@/api/hmmm/companys";
import { list as listTg } from "@/api/hmmm/tags";
import { direction } from "@/api/hmmm/constants";
import { detail, add, update } from "@/api/hmmm/questions";
import { provinces, citys } from "@/api/hmmm/citys";
export default {
  name: "questionsList",
  components: { quillEditor },
  data() {
    //自定义校验规则
    const checkVideoURL = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入视频地址"));
      }
      setTimeout(() => {
        let url = value.match(
          /([\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?)/g
        );
        if (url) {
          if (value.length > 300) {
            callback(new Error("地址长度限制300位以内"));
          } else {
            callback();
          }
        } else {
          callback(new Error("请输入正确的视频地址"));
        }
      });
    };
    return {
      // 辅助值
      isRight: null,
      imageUrl: "",
      // 基本值
      subjectList: [],
      directorysList: [],
      subToDirList: [],
      companysList: [],
      provincesList: [],
      citysList: [],
      // comToCityList: [],
      tagsList: [],
      subToTgList: [],
      directionList: direction,
      //清空设置
      clearable: true,
      // editer配置
      editorOption: {
        placeholder: "请输入文章内容",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            [{ list: "ordered" }, { list: "bullet" }],
            ["blockquote"],
            ["code-block", "image", "link"]
          ]
        }
      },
      //校验规则
      rules: {
        subjectID: [
          { required: true, message: "请选择学科", trigger: "change" }
        ],
        catalogID: [
          { required: true, message: "请选择目录", trigger: "change" }
        ],
        tags: [
          { required: true, message: "请选择试题标签", trigger: "change" }
        ],
        enterpriseID: [
          { required: true, message: "请选择企业", trigger: "change" }
        ],
        province: [
          { required: true, message: "请选择省市", trigger: "change" }
        ],
        direction: [
          { required: true, message: "请选择方向", trigger: "change" }
        ],
        questionType: [
          { required: true, message: "请选择活动区域", trigger: "change" }
        ],
        difficulty: [
          { required: true, message: "请选择活动区域", trigger: "change" }
        ],
        question: [{ required: true, message: "请输入题干", trigger: "blur" }],
        videoURL: [
          {
            required: true,
            validator: checkVideoURL,
            trigger: "blur"
          }
        ],
        answer: [
          { required: true, message: "请输入答案解析", trigger: "blur" }
        ],
        remarks: [
          { required: true, message: "请输入试题备注", trigger: "blur" }
        ]
      },
      // 数据上传
      data: {
        subjectID: "",
        catalogID: "",
        tags: "",
        enterpriseID: "",
        province: "",
        city: "",
        direction: "",
        questionType: "1",
        difficulty: "1",
        question: "",
        videoURL: "",
        answer: "",
        remarks: "",
        options: [
          {
            code: "",
            title: "",
            img: "",
            isRight: false
          },
          {
            code: "",
            title: "",
            img: "",
            isRight: false
          },
          {
            code: "",
            title: "",
            img: "",
            isRight: false
          },
          {
            code: "",
            title: "",
            img: "",
            isRight: false
          }
        ]
      }
    };
  },
  created() {
    this.getSubjectInfo();
    this.getDirectorysInfo();
    this.getCompanys();
    this.cityList();
    this.getTags();
    if (this.$route.query.id) {
      this.getQustionsDetail(this.$route.query.id);
    }
  },
  filters: {
    toString(value) {
      return value + "";
    },
    numberToCode(value) {
      switch (value) {
        case 0:
          return "A";
        case 1:
          return "B";
        case 2:
          return "C";
        case 3:
          return "D";
        case 4:
          return "E";
        case 5:
          return "F";
      }
    }
  },
  //监听 城市下拉
  watch: {
    "data.province": function(cit) {
      this.citysList = citys(cit);
    }
  },
  methods: {
    cityList() {
      const pro = provinces();
      // console.log(pro);
      this.provincesList = pro;
    },
    //获取题库列表
    async getQustionsDetail(id) {
      const { data: res } = await detail({ id });
      // 基本信息初始化
      this.data = res;
      // this.comToCity();
      this.subToDir();
    },
    //学科列表
    async getSubjectInfo() {
      const { data: res } = await simple();
      // console.log(res);
      this.subjectList = res;
    },
    //目录列表
    async getDirectorysInfo() {
      const { data: res } = await listDir();
      // console.log(res.items);
      this.directorysList = res.items;
    },
    subToDir() {
      // subjectList 学科
      // directorysList
      // 根据学科id选相应目录
      this.subToDirList = this.directorysList.filter(
        item => item.subjectID === this.data.subjectID
      );
      //学科关联的标签
      this.subToTgList = this.tagsList.filter(
        item => item.subjectID === this.data.subjectID
      );
    },
    //企业列表
    async getCompanys() {
      const { data: res } = await listCom();
      this.companysList = res.items;
      // console.log(res.items);
    },

    //标签列表
    async getTags() {
      const { data: res } = await listTg();
      // console.log(res.items);
      this.tagsList = res.items;
    },
    checkContent() {
      //富文本的校验 需要 借助 validateField() 方法来触发
      this.$refs.form.validateField("content");
    },
    // 添加选项
    addSelectItem() {
      if (this.data.options.length < 6) {
        this.data.options.push({
          code: "",
          title: "",
          img: "",
          isRight: false
        });
      } else {
        return;
      }
    },
    //删除选项
    delSelectItem(index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (this.data.options.length > 2) {
            this.data.options.splice(index, 1);
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          } else {
            this.$message({
              type: "error",
              message: "删除失败!"
            });
            return;
          }
        })
        .catch(e => {
          this.$message.error("删除失败");
        });
    },
    //上传图片
    upSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(this.imageUrl);
    },
    befUpload() {},
    // 单选答案确定
    makeSureIsRight() {
      this.data.options = this.data.options.map((item, index) => {
        if (index == this.isRight) {
          item.isRight = true;
        } else {
          item.isRight = false;
        }
        return item;
      });
    },
    //提交
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          add(this.data).then(res => {
            // console.log(res);
            this.$message.success("提交成功");
            this.$router.push("/questions/list");
          });
        } else {
          this.$message.error("提交失败");
          return false;
        }
      });
    },
    //修改试题
    editQuestions() {
      // id载入
      this.data.id = Number(this.$route.query.id);
      update(this.data).then(res => {
        this.$message.success("修改成功");
        this.$router.push("/questions/list");
      });
    }
  }
};
</script>

<style scoped lang='scss'>
.avatar-uploader {
  width: 100px;
  height: 60px;
  border: 1px dashed #ddd;
  line-height: 35px;
  border-radius: 5px;
  text-align: center;
  margin-left: 5px;
  display: inline-block;
  position: relative;
  cursor: pointer;
}
.addBtn {
  margin-top: 20px;
}
.del-ico {
  position: absolute;
  font-size: 18px;
  color: #ccc;
  background-color: #fff;
  top: -6px;
  right: -6px;
}
</style>
<style lang="scss">
.ql-editor {
  height: 200px;
}
.quill-editor {
  margin-left: -10px;
}
</style>
